package com.thingple.usb.session;

import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbManager;
import android.util.Log;

import com.thingple.usb.listener.SessionTraceListener;
import com.thingple.usb.listener.StreamDownListener;
import com.thingple.usb.listener.StreamUpListener;
import com.thingple.usb.manager.UsbErrorListener;
import com.thingple.util.Strings;

public abstract class AbstractUsbSession implements UsbSession {

    private static final String TAG = AbstractUsbSession.class.getName();
    protected UsbAccessory device;
    protected UsbManager usbManager;
    protected SessionTraceListener traceListener;
    protected StreamDownListener streamDownListener;
    protected StreamUpListener streamUpListener;
    protected UsbErrorListener errorListener;

    public UsbAccessory getDevice() {
        return device;
    }

    @Override
    public void setStreamUpListener(StreamUpListener listener) {
        streamUpListener = listener;
    }
    @Override
    public void setStreamDownListener(StreamDownListener listener) {
        streamDownListener = listener;
    }
    @Override
    public void setErrorListener(UsbErrorListener listener) {
        errorListener = listener;
    }
    @Override
    public void setTraceListener(SessionTraceListener listener) {
        traceListener = listener;
    }

    protected void onErr(Exception e) {
        Log.d(TAG, e.toString());
        e.printStackTrace();

        if (errorListener != null) {
            errorListener.onErr(e);
        }
    }

    protected void onTx(byte[] bytes, int n, boolean async) {
        Log.d(TAG, "tx:" + Strings.hex(bytes));
        if (streamDownListener != null) {
            streamDownListener.onWrite(bytes, n, async);
        }
    }
    protected void onRx(byte[] bytes, int n) {

        Log.d(TAG, "rx:" + Strings.hex(bytes));
        if (streamUpListener != null) {
            streamUpListener.onData(bytes, n);
        }
    }
    protected void onTrace(String content) {
        if (traceListener != null) {
            traceListener.onTrace(content);
        }
    }

    /**
     * post construct
     */
    protected abstract void init();

    public void destroy() {
        errorListener = null;
        streamUpListener = null;
        streamDownListener = null;
        traceListener = null;
        device = null;
        usbManager = null;
    }
}
